package logic

import (
	"api/model/order_food_goods"
	"api/service"
	"api/utils"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderFoodGoodsAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodGoodsAddLogic {
	return &OrderFoodGoodsAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderFoodGoodsAddLogic) OrderFoodGoodsAdd(req *types.RequestOrderFoodGoodsAdd) (resp *types.ResponseMsg, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	goodsModel := order_food_goods.NewOrderFoodGoodsModel(conn)

	busService := service.NewBusinessService(l.ctx, l.svcCtx)
	bus := busService.GetLoginBusinessInfo()

	ret, err := goodsModel.Insert(l.ctx, &order_food_goods.OrderFoodGoods{
		CategoryId:     req.CategoryId,
		Title:          req.Title,
		Price:          req.Price,
		Img:            req.Img,
		Amount:         req.Amount,
		BusinessId:     bus.Id,
		Specifications: req.Specifications,
		Properties:     req.Properties,
		Jialiao:        req.Jialiao,
		Des:            req.Des,
		Status:         1,
		CreateAt:       utils.GetCurDateTime(),
	})

	if err != nil {
		fmt.Println(err.Error())
		return service.ReturnError()
	}

	// 保存商品至redis
	redis := l.svcCtx.RedisPool.Get()
	defer redis.Close()

	goodsService := service.NewOrderFoodService(l.ctx, l.svcCtx)
	id, _ := ret.LastInsertId()
	goodsService.SaveGoods(redis, bus.Id, req.CategoryId, &service.OrderFoodGoods{
		Id:             id,
		Title:          req.Title,
		Price:          req.Price,
		Img:            req.Img,
		Specifications: req.Specifications,
		Properties:     req.Properties,
		Jialiao:        req.Jialiao,
		Des:            req.Des,
	})

	return service.ReturnOk()
}
